import measuringPhaseEnum from "../enum/measuringPhase.enum"
import MeasurementCreator from "./MeasurementCreator"
import re from "../packages/60039"
import ConstrainedHit from "../utils/ConstrainedHit"
import Le from "../math/13188"
import { PointerMoveEvent } from "../event/PointerEvent"
import { ClickEvent } from "../event/GestureEvent"
import Ne from "../packages/76870"
import InputIniModule from "../module/InputIniModule"
export default class MeasurementCreatorDesktop extends MeasurementCreator {
  continuous: () => boolean
  onCreate: (e: ConstrainedHit) => void
  onMouseMove: () => void
  onMouseClick: (e: any) => void
  constructor(e, t, i: InputIniModule["registerUnfilteredHandler"], s, n, r, o, a, h, l, d) {
    super(e, t, s, n, r, o, a, h, d)
    this.continuous = l
    this.onCreate = async ext => {
      const t = this.previousPoint.distanceTo(ext._point) > re.yV
      if (t || 2 !== this.currentLinePoints) {
        if (this.getPhase() === measuringPhaseEnum.CREATING) {
          this.createNewLine(ext)
          return this.addPointToLine(ext), void this.setPhase(measuringPhaseEnum.CREATING_NEXT_POINT)
        }
        t && this.getPhase() === measuringPhaseEnum.CREATING_NEXT_POINT && (this.updateLastPoint(ext), this.addPointToLine(ext))
      } else {
        const t = {
            origin: ext.point.addScaledVector(ext.normal, 0.05),
            normal: ext.normal
          },
          i = this.pointer.getMeshIntersection(t)

        if (i) {
          this.points.pop()
          const e = new ConstrainedHit(i, Le.l1.Free)
          this.addPointToLine(e), this.addPointToLine(e), this.setPhase(measuringPhaseEnum.CREATING_NEXT_POINT)
        }
      }
    }
    this.onMouseMove = () => {
      if (this.getPhase() === measuringPhaseEnum.CREATING_NEXT_POINT) {
        const e = this.getIntersection()
        e && this.updateLastPoint(e)
      }
    }
    this.onMouseClick = e => {
      if (e.button !== Ne.MP.PRIMARY || this.getPhase() === measuringPhaseEnum.IDLE) return
      const t = this.getIntersection()

      this.onCreate(t)
    }
    this.inputSubscriptions.push(i(PointerMoveEvent, this.onMouseMove), i(ClickEvent, this.onMouseClick))
    this.cancelSubs()
  }
  start() {
    super.start()
  }
  stop() {
    this.getPhase() === measuringPhaseEnum.CREATING_NEXT_POINT && (this.points.pop(), this.currentLinePoints < 3 && this.points.pop())
    super.stop()
  }
  finishLine(e) {
    this.points.pop()
    this.addPointToLine(e)
    this.setPhase(measuringPhaseEnum.CREATING)
    this.onDone()
  }
}
